﻿using GPSTracker.Helper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace GPSTracker.Views.Report
{
    public partial class ImageURL : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["DeID"] != null)
            {
                Byte[] image = this.GetData(Convert.ToInt32(Request.QueryString["DeID"]), Request.QueryString["CallFrom"].ToString());
                this.WriteBinaryImage(image);
            }
        }

        void WriteBinaryImage(byte[] image)
        {
            if (image != null)
            {
                Response.ContentType = "image/png";

                using (MemoryStream ms = new MemoryStream(image))
                {
                    using (Bitmap bmp = (Bitmap)Bitmap.FromStream(ms))
                    {
                        bmp.Save(Response.OutputStream, ImageFormat.Png);
                    }
                }
            }

            Response.End();
        }

        private byte[] GetData(int DeID, string callFrom)
        {
            try
            {
                var cmd = new SqlCommand();
                cmd.Connection = CommonFx.GetSqlCon();
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "SP_GetDeliveryStatusByDeID";

                cmd.Parameters.Add(new SqlParameter("@pDeID", DeID));
                cmd.Parameters.Add(new SqlParameter("@pCallFrom", callFrom));

                cmd.Parameters.Add("@pImage", SqlDbType.VarBinary, 200000000);                

                cmd.Parameters.Add("@pIsErrorFound", SqlDbType.Bit);
                cmd.Parameters.Add("@pErrorMessage", SqlDbType.NVarChar, 4000);

                cmd.Parameters["@pImage"].Direction = ParameterDirection.Output;

                cmd.Parameters["@pIsErrorFound"].Direction = ParameterDirection.Output;
                cmd.Parameters["@pErrorMessage"].Direction = ParameterDirection.Output;

                cmd.ExecuteNonQuery();

                if (!Convert.ToBoolean(cmd.Parameters["@pIsErrorFound"].Value))
                {
                    object obj = cmd.Parameters["@pImage"].Value;

                    if (obj != null)
                        return (Byte[])obj;
                    else
                        return null;
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {
                CommonDAL.ErrorDAL.ErrorLog(ex.Message, "Image URL", "GetData");
                return null;
            }
        }
    }
}